const express = require('express');
const { buildSchema } = require('graphql');
const { graphqlHTTP } = require('express-graphql');

const DB = {
  userlist: [],
};

const schema = buildSchema(`
  input UserInput {
    name: String
    age: Int
  }
  type User {
    id: ID,
    name: String,
    age: Int
  }
  type Query {
    getUsers: [User]
  }
  type Mutation {
    createUser(user: UserInput): User
    updateUser(id: ID!, user: UserInput): User
  }
`);

const root = {
  getUsers() {
    return DB.userlist || [];
  },
  createUser({ user }) {
    DB.userlist.push({ id: Math.random().toString(16).substr(2), ...user });
    return DB.userlist.slice(-1)[0];
  },
  updateUser({ id, user }) {
    let res = null;
    DB.userlist.forEach((item, index) => {
      if (item.id === id) {
        DB.userlist[index] = Object.assign({}, item, { id, ...user });
        res = DB.userlist[index];
      }
    });
    return res;
  },
};

const app = express();

const middleware = (req, res, next) => {
  console.log(req, res);
  next();
};

app.use(middleware);

app.use(
  '/api/graphql',
  graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true,
  })
);

app.listen(3000, () => {
  console.log('server is running in http://localhost:3000/api/graphql');
});
